package com.bright.ghj.overt.service.impl;

import com.bright.ghj.overt.pojo.vo.SaveFileResultVO;
import com.bright.ghj.overt.service.StoreFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author hxj
 * @Date 2024/3/8 11:45
 * @Description
 */
@Component
@RequiredArgsConstructor
@Qualifier("mongoDBStoreFile")
@ConditionalOnProperty(name = "store.type", havingValue = "mongoDB")
public class MongoDBStoreFileServiceImpl implements StoreFileService {

    private final RestTemplate restTemplate;

    /**
     * 平台网址
     */
    @Value("${store-mongodb.urlHead}")
    private String storeUrlHead;

    /**
     * 龙哥附件中心地址 /store/file
     */
    @Value("${store-mongodb.url}")
    private String storeUrl;

    /**
     * 文件网址前缀 /store/file/
     */
    @Value("${store-mongodb.fileUrlPrefix}")
    private String fileUrlPrefix;

    @Override
    public List<SaveFileResultVO> saveFile(List<MultipartFile> files, String baseDir) throws IOException {
        List<SaveFileResultVO> saveFileResultVOS = new ArrayList<>();


        //设置请求头，请求类型为json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> dataParam = new LinkedMultiValueMap<>();
        for (MultipartFile file : files) {
            byte[] fileData = file.getBytes();
            ByteArrayResource fileAsResource = new ByteArrayResource(fileData) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }

                @Override
                public long contentLength() {
                    return fileData.length;
                }
            };

            dataParam.add("file", fileAsResource);
        }


        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(dataParam, headers);
        ResponseEntity<Map> exchange = restTemplate.exchange(storeUrlHead + storeUrl, HttpMethod.POST, request, Map.class);
        Map body = exchange.getBody();
        Map data = (Map) body.get("data");
        List<Map> fileInfos = (List<Map>) data.get("fileInfos");
        int i = 0;
        for (Map fileInfo : fileInfos) {
            String newFileName = (String) fileInfo.get("id");

            SaveFileResultVO saveFileResultVO = new SaveFileResultVO();
            saveFileResultVO.setUploadPath(fileUrlPrefix);
            saveFileResultVO.setNewFileName(newFileName);
            saveFileResultVO.setOldFileName(files.get(i).getOriginalFilename());

            saveFileResultVOS.add(saveFileResultVO);
            i++;
        }

        return saveFileResultVOS;
    }

}
